import time
import cv2
import uiautomation as auto
from zz import zz_code, zz_str, zz_img, zz_img_cv
from game import zz_game
import cv2
from pynput.keyboard import Key, Controller as KeyboardController


# 使用小地图判断next
# 需要传入当前第几张图
def capture():
    # 截图保存
    auto.uiautomation.SetGlobalSearchTimeout(3)  # 设置全局搜索超时 5

    window = auto.PaneControl(searchDepth=1, ClassName='地下城与勇士')  # search 2 times
    window.SetTopmost(False)
    # window.Click()

    img_path = zz_game.get_pc_temp_file()
    window.CaptureToImage(img_path)
    return img_path


def main():
    img_src = './../_tmp/pc_temp.png'
    # img_src = ''
    if zz_str.is_null_or_empty(img_src):
        img_src = capture()

    t_begin = zz_code.date_now()
    # img_arr = cv2.imread(img_src)
    img_arr = zz_img_cv.load_img(img_src)
    g = zz_game.Game(None)
    g.set_play_index(1)

    # r = zz_img_cv.find_img(zz_game.get_pc_temp_file(), "./game/img/mini_map_begin.png", 0.9)
    # print(r.to_json())
    # begin_x, begin_y = r.get_data("first")
    begin_x, begin_y = [948, 52]

    # r = zz_img_cv.find_img(zz_game.get_pc_temp_file(), "./game/img/mini_map_end.png", 0.9)
    # print(r.to_json())
    # end_x, end_y = r.get_data("first")
    end_x, end_y = [1021, 70]

    x, y = min(end_x, begin_x), min(end_y, begin_y)
    w, h = (107, 36)

    print(x, y)
    print(begin_x, begin_y)
    mini_map = img_arr[y:y + h, x:x + w]
    mini_map_data = [
        {
            "key": Key.right
        },
        {
            "key": Key.right
        },
        # {
        #     "key": Key.down
        # },
        {
            "key": Key.right
        },
    ]

    cv2.imshow("preview", mini_map)
    cv2.resizeWindow("preview", 200, 80)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    init_xy = (abs(begin_x - x), abs(begin_y - y))
    print(init_xy)
    r = g.mini_map_from_next(init_xy, mini_map, mini_map_data)
    print(r.to_json())
    t_end = zz_code.date_now()
    print(f"ms: {(t_end - t_begin).microseconds / 1000}")
    # cv2.rectangle(mini_map, (0, 0), (0 + 17, 0 + 17), (0, 0, 255), 1)

    # cv2.imwrite(f'./../_tmp/game_next.png', mini_map)
    cv2.imshow("preview", mini_map)
    cv2.resizeWindow("preview", 200, 80)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main()
